<template>
  <div class="">
    <top :companyInfo="comInfo" @goBack="goBack"/>
    <div class="basicInfo">
      <p class="title">筛选条件</p>
      <div class="select">
        <p class="selectType">
          <span>风险类型：</span><span
            @click="handlActiveOne('all')"
            :class="[{ cur: activeSelectOne == 'all' }]"
          >全部</span><span
            @click="handlActiveOne(ite.value)"
            :class="[{ cur: activeSelectOne == ite.value }]"
            v-for="(ite, i) in dataFXDL"
            :key="ite + i"
          >{{ ite.label }}</span>
        </p>
        <p class="selectType">
          <span>风险等级：</span><span
            @click="handlActiveTwo('all')"
            :class="[{ cur: activeSelectTwo == 'all' }]"
          >全部</span><span
            @click="handlActiveTwo(ite.value)"
            :class="[{ cur: activeSelectTwo == ite.value }]"
            v-for="(ite, i) in dataYJDJ"
            :key="ite + i"
          >{{ ite.label }}</span>
        </p>
        <p class="selectType">
          <span>时　　间：</span><span
            @click="handlActiveTree('all')"
            :class="[{ cur: activeSelectTree == 'all' }]"
          >全部</span><span
            @click="handlActiveTree(ite.fieldCode)"
            :class="[{ cur: activeSelectTree == ite.fieldCode }]"
            v-for="(ite, i) in selectOptions3"
            :key="ite + i"
          >{{ ite.fieldName }}</span>
          <el-date-picker
            v-model="daterange"
            v-if="activeSelectTree === '自定义'"
            format='yyyy-MM-dd'
            value-format='yyyy-MM-dd'
            type="daterange"
            size="mini"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="daterangeChange">
          </el-date-picker>
        </p>
      </div>
      <p class="title">风险列表</p>
      <el-table
        :data="tableDataTwo"
        border
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{ background: '#f2f9fe' }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ (pageNumTwo - 1) * 10 + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="企业名称"
          prop="qymc"
          align="center"
        ></el-table-column>
        <el-table-column
          label="风险类型"
          prop="fxdl"
          align="center"
          :formatter="fxdlFormat"
        ></el-table-column>
        <el-table-column
          label="风险名称"
          prop="yjxl"
          align="center"
        ></el-table-column>
        <el-table-column
          label="风险等级"
          prop="yjdj"
          align="center"
          :formatter="yjdjFormat"
        >
        </el-table-column>
        <el-table-column
          label="发生时间"
          prop="yjTime"
          align="center"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click.stop="handleCheck(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="风险详情"
          prop="yjxq"
          align="center"
          show-overflow-tooltip
        ></el-table-column> -->
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="sizeChangeTwo"
          @current-change="pageChangeTwo"
          :current-page="pageNumTwo"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSizeTwo"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalTwo"
        ></el-pagination>
      </div>
      <!-- <div class="button">
        <el-button
          type="primary"
          @click="goBack"
        >返回上页</el-button>
      </div> -->
    </div>

    <!-- 查看详情 -->
    <el-dialog
      title="查看详情"
      :visible.sync="dialogVisible"
      width="40%"
      custom-class="dialog"
      center
    >
      <el-form
        :model="detailData"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="企业名称:">
          <span>{{ detailData.qymc }}</span>
        </el-form-item>
        <el-form-item label="风险类型:">
          <span>{{ fxdlFormat(detailData) }}</span>
        </el-form-item>
        <el-form-item label="风险名称:">
          <span>{{ detailData.yjxl }}</span>
        </el-form-item>
        <el-form-item label="风险等级:">
          <span>{{ yjdjFormat(detailData) }}</span>
        </el-form-item>
        <el-form-item label="发生时间:">
          <span>{{ detailData.yjTime ? detailData.yjTime.slice(0, 11) : detailData.yjTime }}</span>
        </el-form-item>
        <el-form-item label="风险详情:">
          <span>{{ detailData.yjxq }}</span>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button
          @click="dialogVisible = false"
          type="primary"
        >关闭</el-button>
      </div>
    </el-dialog>
    <!-- 授权协议 -->
    <el-dialog
      title="授权协议"
      :visible.sync="dialogLicense"
      width="540px"
      custom-class="dialog"
    >
      <el-image
        v-for="item in imgList"
        :key="item"
        style="width: 500px; height: 500px"
        :src="item"
        :preview-src-list="imgList"
      ></el-image>
    </el-dialog>
    <!-- 下载分控报告提示框 -->
    <el-dialog
      title=""
      :visible.sync="dialogVisible1"
      width="30%"
    >
      <p class="downMsg">
        您的下载申请稍后将提交至征信公司，审核通过后风控报告将发送至您的邮箱，请确认邮箱地址是否正确。
      </p>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="邮箱 "
          prop="email"
        >
          <el-input
            v-model="ruleForm.email"
            style="width: 200px"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters,mapActions } from 'vuex'
import { getField } from '@/api/user.js'
import { moveToWhiteFormRecmd, getW, delW, getQyfx,updateQyhxHistoryReaded } from '@/api/manager.js'
import {
  getCbInfo,
  getZsfxPage,
  relationCo,
  sqStatus,
  qySign,
  getUser,
  submitApprove,
  searchAuthByShtyxydm,
  relatChild,
  zsfxxlCount,
  jyyc,
} from '@/api/portay'
import mixin from '@/views/roles/admin/work/mixin'
import top from './header.vue'
export default {
 components:{top},
  props:['companyInfo','type'],
  mixins: [mixin],
  data() {
    return {
      comInfo: this.companyInfo,
      companyName: undefined,
      shtyxydm: undefined,
      sqStatu: '已授权',
      nsrType: undefined,
      qylxOptions: [],
      /* 筛选栏 */
      currentSelect1: 'all',
      currentSelect2: 'all',
      selectOptions1: [],
      selectOptions2: [],
      //列表数据
      dataList: [],
      dialogName: undefined,
      dialogVisible: false,
      dialogVisible1: false,
      ruleForm: {
        email: '',
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
      },
      detailData: [],
      dialogLicense: false,
      imgList: [],
      loading: false,
      pagination: { page: 1, total: 0 },
      isdy: false, //是否订阅
      jyycData: {},
      busVisible: false,
      cymList: [],
      nameVisible: false,
      //新增
      dataFXDL: [],
      dataYJDJ: [],
      activeSelectOne: 'all',
      activeSelectTwo: this.type,
      selectOptions3: [
        { fieldCode: '0', fieldName: '今天', num: 0 },
        { fieldCode: '7', fieldName: '近7天', num: 0 },
        { fieldCode: '30', fieldName: '近30天', num: 0 },
        { fieldCode: '自定义', fieldName: '自定义', num: 0 },
      ],
      daterange:[],
      activeSelectTree: 'all',
      pageNumTwo: 1,
      pageSizeTwo: 10,
      totalTwo: 0,
      tableDataTwo: [],
    }
  },
  filters: {
    qylxFilter(val, option) {
      if (!val) return ''
      return option
        .filter((item) => item.value == val)
        .map((ite) => ite.label)[0]
    },
  },
  computed: {
    ...mapGetters([
      'token',
    ])
  },
  created() {
    let params = {
      page: 1,
      size: 100,
      code: 'QYLX',
    }
    getField(params).then((res) => {
      if (res.status) {
        this.qylxOptions = res.data.records.map((item) => {
          return { label: item.fieldName, value: item.fieldCode }
        })
      }
    })
    //this.getDict();
    //this.shtyxydm = this.$route.query.shtyxydm;
    //this.selectOptions1 = this.$route.query.zsfxData
    //this.comInfo = JSON.parse(sessionStorage.getItem('comInfo'))
    let index = this.comInfo.qymc.indexOf('淄博市')
    if (index == 0) {
      this.companyName = this.comInfo.qymc.substr(3, 4)
    } else {
      this.companyName = this.comInfo.qymc.substr(0, 4)
    }
    this.getJyyc()
    this.cymList = this.comInfo.cym ? this.comInfo.cym.split(';') : []
    this.getQyFx()
    //this.getSqStatus();
    this.qySign()
    //this.getIsDy()
    this.getDictDataList()
  },
  mounted() {},
  methods: {
    ...mapActions([
      'getWebSocketDataList','websocketonmessage'
    ]),
    sizeChangeTwo(val) {
      this.pageSizeTwo = val
      this.pageNumTwo = 1
      this.getQyFx()
    },
    pageChangeTwo(val) {
      this.pageNumTwo = val
      this.getQyFx()
    },
    async getDictDataList() {
      const dataYJDJ = await this.$store.dispatch('asyncApi/getDict', {
        code: 'YJDJ',
      })
      this.dataYJDJ = dataYJDJ
      const dataFXDL = await this.$store.dispatch('asyncApi/getDict', {
        code: 'HXFXDL',
      })
      this.dataFXDL = dataFXDL
    },
    //获取近N天日期
    getPreviousDate(numOfDays) {
      var date = new Date()
      date.setDate(date.getDate() - numOfDays)
      var year = date.getFullYear()
      var month = date.getMonth() + 1 < 10 ? '0'+(date.getMonth() + 1) : date.getMonth() + 1;
      var day = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
      return `${year}-${month}-${day}`
    },
    getNewDate() {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1 < 10 ? '0'+(date.getMonth() + 1) : date.getMonth() + 1;
      var day = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
      return `${year}-${month}-${day}`
    },
    //格式化
    fxdlFormat(row) {
      for (let i = 0; i < this.dataFXDL.length; i++) {
        if (this.dataFXDL[i].value == row.fxdl) {
          return this.dataFXDL[i].label
        }
      }
    },
    yjdjFormat(row) {
      for (let i = 0; i < this.dataYJDJ.length; i++) {
        if (this.dataYJDJ[i].value == row.yjdj) {
          return this.dataYJDJ[i].label + '风险'
        }
      }
    },
    //企业风险
    getQyFx() {
      let params = {
        pageSize: this.pageSizeTwo,
        pageNum: this.pageNumTwo,
        qymc: this.comInfo.qymc,
      }
      if (this.activeSelectOne == 'all') {
        delete params['fxdl']
      } else {
        params['fxdl'] = this.activeSelectOne
      }
      if (this.activeSelectTwo == 'all') {
        delete params['yjdj']
      } else {
        params['yjdj'] = this.activeSelectTwo
      }
      if (this.activeSelectTree == 'all') {
        delete params['startTime']
        delete params['endTime']
      } else  if(this.activeSelectTree == '自定义'){
        params['startTime'] = this.daterange[0]
        params['endTime'] = this.daterange[1]
      }else {
        params['startTime'] = this.getPreviousDate(this.activeSelectTree)
        params['endTime'] = this.getNewDate()
      }
      this.loading = true
      getQyfx(params).then((res) => {
        if (res.status) {
          this.loading = false
          let newObj = JSON.parse(JSON.stringify(res.data))
          this.totalTwo = newObj.total ? Number(newObj.total) : 0
          this.tableDataTwo = res.data.records ? res.data.records : []
        }else{
          this.loading = false
        }
      })
    },
    zsfxChange(val) {
      this.pagination.page = val
      this.getQyFx()
    },
    //测试
    handlActiveOne(val) {
      if (this.activeSelectOne == val) return
      this.activeSelectOne = val
      this.pageNumTwo = 1
      this.getQyFx()
    },
    handlActiveTwo(val) {
      if (this.activeSelectTwo == val) return
      this.activeSelectTwo = val
      this.pageNumTwo = 1
      this.getQyFx()
    },
    handlActiveTree(val) {
      if (this.activeSelectTree == val) return
      this.activeSelectTree = val
      if (val == '自定义'){
        this.daterange = []
        return
      } 
      this.pageNumTwo = 1
      this.getQyFx()
    },
    daterangeChange(){
      if(!(this.daterange))return 
      this.pageNumTwo = 1
      this.getQyFx()
    },
    //判断是否为统一社会信用代码
    handelCode(val) {
      if (val.length == 18 && val.startsWith('91')) {
        return '统一社会信用代码：'
      } else if (val.length == 7) {
        return '企业编号'
      } else {
        return '工商注册号：'
      }
    },
    //查看是否已订阅
    getIsDy() {
      getW({ shtyxydm: this.comInfo.shtyxydm }).then((res) => {
        if (res.status) {
          if (res.data.records.length > 0) {
            this.isdy = true
          } else {
            this.isdy = false
          }
        } else {
          this.$message({
            type: 'error',
            message: `${res.msg}`,
          })
        }
      })
    },
    //订阅
    handelDy() {
      moveToWhiteFormRecmd(this.comInfo.shtyxydm).then((res) => {
        if (res.status) {
          this.isdy = true
          this.$message({
            type: 'success',
            message: `${res.msg}`,
          })
        } else {
          this.$message({
            type: 'error',
            message: `${res.msg}`,
          })
        }
      })
    },
    //取消订阅
    handelDeleteDy() {
      delW({
        shtyxydm: this.comInfo.shtyxydm,
      }).then((res) => {
        if (res.status) {
          this.isdy = false
          this.$message({
            type: 'success',
            message: `${res.msg}`,
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
          })
        }
      })
    },
    //经营异常
    getJyyc() {
      jyyc({
        TYSHXYDM: this.comInfo.shtyxydm,
      }).then((res) => {
        if (res.status) {
          this.jyycData = res.data
        }
      })
    },
    async getDict() {
      const dataHXFXDL = await this.$store.dispatch('asyncApi/getDict', {
        code: 'HXFXDL',
      })
      this.selectOptions1 = dataHXFXDL
      const dataHXFXXL = await this.$store.dispatch('asyncApi/getDict', {
        code: 'HXFXXL',
      })
      this.selectOptions2 = dataHXFXXL
    },
    //查看企业授权
    goLicense() {
      if (this.sqStatu == '已授权') {
        let params = {
          shtyxydm: this.comInfo.shtyxydm,
        }
        this.imgList = []
        searchAuthByShtyxydm(params).then((res) => {
          this.dialogLicense = true
          //this.licenseData = res.data;
          res.data.fileList.map((item) => {
            return this.run(item.base64Code, res.data.printBk)
          })
        })
        let comInfo = this.comInfo
        this.$router.push({
          path: '/portray1/license',
          query: { shtyxydm: comInfo.shtyxydm, page: 'selfRisk' },
        })
      } else {
        this.$message({
          message: `企业未授权`,
          type: 'warning',
        })
      }
    },
    // 添加水印1
    async run(imgUrl, markText) {
      // 1.图片路径转成canvas
      const tempCanvas = await this.imgToCanvas(imgUrl)
      // 2.canvas添加水印
      //const markText = '我是水印'
      const canvas = this.addWatermark(tempCanvas, markText)
      // 3.canvas转成img
      const img = this.convasToImg(canvas)
      // 查看效果
      this.imgList.push(img.src)
    },
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let params = {
            qyshxydm: this.comInfo.shtyxydm,
            recvEmail: this.ruleForm.email,
          }
          submitApprove(params).then((res) => {
            this.dialogVisible1 = false
            if (res.status) {
              this.$message({
                type: 'success',
                message: res.msg,
              })
            } else {
              this.$message({
                type: 'error',
                message: res.msg,
              })
            }
          })
        }
      })
    },
    //点击筛选项
    async handelClick1(val) {
      if (this.currentSelect1 == val) return
      this.currentSelect1 = val
      this.pagination.page = 1
      this.currentSelect2 = 'all'
      if (val == 'all') {
        this.selectOptions2 = []
      } else {
        const xlData = await relatChild({ PCode: 'HXFXDL', PId: val })
        const xlCount = await zsfxxlCount({ TYSHXYDM: this.comInfo.shtyxydm })
        xlData.data.forEach((item) => {
          let index = xlCount.data.findIndex(
            (ite) => item.fieldCode == ite.xldm
          )
          if (index > -1) {
            item.num = xlCount.data[index].num
          } else {
            item.num = 0
          }
        })
        this.selectOptions2 = xlData.data
      }
      this.getQyFx()
    },
    handelClick2(val) {
      if (this.currentSelect2 == val) return
      this.currentSelect2 = val
      this.pagination.page = 1
      this.getQyFx()
    },
    //纳税人标识
    qySign() {
      qySign({ TYSHXYDM: this.comInfo.shtyxydm }).then((res) => {
        this.nsrType = res.data[0].aji == '是' ? 'A级纳税人' : undefined
      })
    },
    //企业授权状态
    getSqStatus() {
      sqStatus({ TYSHXYDM: this.comInfo.shtyxydm }).then((res) => {
        this.sqStatu = res.data
      })
    },

    //下载风控报告
    downLoadRiskReport() {
      let userId = localStorage.getItem('username')
      getUser({ userId }).then((res) => {
        this.dialogVisible1 = true
        this.ruleForm.email = res.data.userEmail
      })

      /* let comInfo = this.comInfo;
            this.$router.push({ path: '/portray1/riskReport',query:{shtyxydm:comInfo.shtyxydm}}); */
    },
    //查看详情
    handleCheck(obj) {
      this.dialogVisible = true
      this.detailData = {...obj}
      updateQyhxHistoryReaded({ id: obj.id }).then((res) => {
        if(res.status){
          this.getWebSocketDataList()
          this.initWebSocket()
        }
      })
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https   key你自定义的key
      //var host = window.location.host  m418160z45.mdo.co:18584
      //let websockUrl="ws://192.168.2.25:9002/jrfk/qyxx/api/websocket/"
      let websockUrl= process.env.VUE_APP_WEB_SOCKET_HOST
      this.websock = new WebSocket(websockUrl + this.token);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketmessage;
      this.websock.onclose = this.websocketclose;
      //this.websock.send("您好啊");
    },
    websocketonopen() {
      console.log("wssuccess");   
    },
    websocketonerror() {
      console.log('wsfail');
    },
    //这个是收到后端主动推送的值
    websocketmessage(e) {
      let dataList = JSON.parse(e.data )
      this.websocketonmessage(dataList)
    },
    websocketclose() {},
    //返回查询
    goBackSearch() {
      this.$router.push({ path: '/portray1/index' })
    },
    //返回上一页
    goBack() {
      //this.$router.go(-1)
      /* let comInfo = this.comInfo;
            this.$router.push({ path: '/portray1/companyMessage'});  */
      this.$emit('back')
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
.app-container {
  background: #f0f0f0;
  padding: 24px;
  font-size: 14px;
}
.select {
  background: #fff;
  border-radius: 10px;
  width: 100%;

  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .selectType {
    padding-left: 24px;
    display: flex;
    align-items: center;
  }
  .selectType span:not(:first-child) {
    display: inline-block;
    margin-right: 20px;
    padding: 6px 8px;
  }
  .selectType span:not(:first-child):hover {
    cursor: pointer;
    background-color: #1890ff;
    color: #fff;
  }
  .selectType .cur {
    background-color: #1890ff !important;
    color: #fff !important;
  }
  .selectType .disable {
    background-color: #fff;
    color: #a6a6a6;
  }
}
.basicInfo {
  background: #fff;
  border-radius: 10px;
  width: 100%;
  min-height: 200px;
  padding: 12px 24px;
  margin-top: 20px;
  .button {
    margin-top: 50px;
    width: 100%;
    text-align: center;
  }
}
.title {
  font-size: 18px;
  font-weight: 900;
}
.msgInfo {
  color: #000;
}
.pray {
  color: #a6a6a6;
}
.glqy {
  color: #4a8bf6;
}
.glqy:hover {
  cursor: pointer;
}
.downMsg {
  width: 100%;
  text-indent: 2em;
  font-size: 16px;
}
</style>
<style>
.dialog {
  border-radius: 10px;
  padding-bottom: 50px;
}
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /*height:600px;*/
  max-height: calc(100% - 200px);
  max-width: calc(100% - 30px);
}
.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
</style>